package com.chuanjiabao.wisdom.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.alibaba.sdk.android.oss.model.GeneratePresignedUrlRequest;
import com.chuanjiabao.wisdom.R;
import com.chuanjiabao.wisdom.adapter.MonthAdapter;
import com.chuanjiabao.wisdom.application.FApplication;
import com.chuanjiabao.wisdom.bean.FamilyFileTotalBean;
import com.chuanjiabao.wisdom.bean.FamilyResCallbackBean;
import com.chuanjiabao.wisdom.bean.ImageBean;
import com.chuanjiabao.wisdom.bean.ReasionInfoCallbackBean;
import com.chuanjiabao.wisdom.bean.RefreshMessageEvent;
import com.chuanjiabao.wisdom.bean.STSCallBackBean;
import com.chuanjiabao.wisdom.databinding.ActivityFamilyResBinding;
import com.chuanjiabao.wisdom.listener.OnBHClickListener;
import com.chuanjiabao.wisdom.listener.RxObserver;
import com.chuanjiabao.wisdom.ui.ActivityStack;
import com.chuanjiabao.wisdom.ui.BaseActivity;
import com.chuanjiabao.wisdom.util.BHThreadPool;
import com.chuanjiabao.wisdom.util.DropPopWindowUtils;
import com.chuanjiabao.wisdom.util.GsonUtil;
import com.chuanjiabao.wisdom.util.HTTPAPI;
import com.chuanjiabao.wisdom.util.LogUtil;
import com.chuanjiabao.wisdom.util.SpResourceUtil;
import com.chuanjiabao.wisdom.util.SpUtils;
import com.chuanjiabao.wisdom.util.StringUtil;
import com.chuanjiabao.wisdom.util.TimeHelper;
import com.chuanjiabao.wisdom.util.ToastUtil;
import com.chuanjiabao.wisdom.util.dialog.DowloadDialog;
import com.chuanjiabao.wisdom.util.dialog.HintDeleteDialog;
import com.chuanjiabao.wisdom.util.dialog.HomeFilesRelevantOperationDialog;
import com.chuanjiabao.wisdom.util.dialog.ShareDialog;
import com.luck.picture.lib.permissions.RxPermissions;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.request.BaseRequest;
import com.lzy.okgo.utils.OkLogger;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;

import static com.alibaba.sdk.android.oss.common.HttpMethod.GET;
import static com.chuanjiabao.wisdom.bean.Constants.REQUEST_CODE;

public class FamilyResActivity extends BaseActivity {

    ActivityFamilyResBinding binding;
    String homeId, peopleId;
    boolean isSHow = false;
    List<FamilyResCallbackBean.DataBeanX.DataBean> listDataSecond = new ArrayList<>();
    List<String> months = new ArrayList<>();
    MonthAdapter monthAdapter;
    OSSClient oss;
    ReasionInfoCallbackBean.DataBean bean;
    String bucketName = "";

    //图片/视频
    List<String> fileIds = new ArrayList<>();
    List<String> fileIdsSecond = new ArrayList<>();
    List<ImageBean> listItemLocations = new ArrayList<>();

    //文本
    List<String> fileIdsText = new ArrayList<>();
    List<String> fileIdsSecondText = new ArrayList<>();
    List<ImageBean> listItemLocationsText = new ArrayList<>();

    Map<String, List<FamilyResCallbackBean.DataBeanX.DataBean>> maps = new HashMap<>();

    //图片/视频/文本
    private String photoUrl = "", photoHint = "0";
    private String videoUrl = "", videoHint = "0";
    private String textUrl = "", textHint = "0";
    private DowloadDialog mDialog;
    private int pos = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_family_res);
        binding.setActivity(this);
        initView();
        initList();
    }

    private void initView() {
        bean = (ReasionInfoCallbackBean.DataBean) SpUtils.getBean("module_reasion");
        peopleId = getIntent().getStringExtra("module_userId");
        homeId = SpResourceUtil.getHomeId();
        if (oss == null) getSTS();
        binding.ivModuleClock.setOnClickListener(this);
        binding.ivModuleDelete.setOnClickListener(this);
        binding.tvModuleAbout.setOnClickListener(this);
        binding.topBarRelative.setOnClickListener(this);
        binding.rightText.setOnClickListener(this);
        binding.tvModuleCheck.setOnClickListener(this);
    }

    private void initList() {
        if ("people".equals(getIntent().getStringExtra("module_from"))) {
            binding.tvModuleCheck.setVisibility(View.GONE);
            isSHow = true;
            binding.rightText.setText("取消");
            binding.llModuleBottom.setVisibility(View.VISIBLE);
        }

        monthAdapter = new MonthAdapter(FamilyResActivity.this, months, maps, isSHow, false);
        binding.recycler.setLayoutManager(new LinearLayoutManager(FamilyResActivity.this));
        binding.recycler.setItemAnimator(new DefaultItemAnimator());
        ((SimpleItemAnimator) binding.recycler.getItemAnimator()).setSupportsChangeAnimations(false);
        binding.recycler.setAdapter(monthAdapter);

        monthAdapter.setOnThirdClickListener((first, second, third, url) -> {
            if (4 == third) {
                //文本
                if (!fileIdsText.contains(second + "")) {
                    fileIdsText.add(second + "");
                    listItemLocationsText.add(new ImageBean(first, second, third));
                } else {
                    fileIdsSecondText = fileIdsText;
                    fileIdsSecondText.remove(second + "");
                    fileIdsText = fileIdsSecondText;

                    List<Integer> indexList = new ArrayList<>();
                    for (ImageBean iv : listItemLocationsText) {
                        if (iv.getFirst() == first && iv.getSecond() == second) {
                            indexList.add(listItemLocationsText.indexOf(iv));
                        }
                    }

                    for (Integer item : indexList) {
                        listItemLocationsText.remove(item.intValue());
                    }
                }
            } else {
                //图/视频
                if (!fileIds.contains(second + "")) {
                    fileIds.add(second + "");
                    listItemLocations.add(new ImageBean(first, second, third, url));
                } else {
                    fileIdsSecond = fileIds;
                    fileIdsSecond.remove(second + "");
                    fileIds = fileIdsSecond;

                    List<Integer> indexList = new ArrayList<>();
                    for (ImageBean iv : listItemLocations) {
                        if (iv.getFirst() == first && iv.getSecond() == second) {
                            indexList.add(listItemLocations.indexOf(iv));
                        }
                    }

                    for (Integer item : indexList) {
                        listItemLocations.remove(item.intValue());
                    }
                }
            }
        });

        binding.refreshLayout.setOnRefreshListener(refreshlayout -> {
            p = 1;
            fileIds.clear();
            fileIdsText.clear();
            listItemLocations.clear();
            listItemLocationsText.clear();
            getFamilyUserInfo(homeId, peopleId, true);
        });

        binding.refreshLayout.setOnLoadMoreListener(refreshlayout -> getFamilyUserInfo(homeId, peopleId, false));

        if ("people".equals(getIntent().getStringExtra("module_from"))) {
            type = getIntent().getStringExtra("module_type");
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvModuleCheck:
                DropPopWindowUtils.showDrop(
                        FamilyResActivity.this,
                        binding.tvModuleCheck,
                        photoUrl, videoUrl, textUrl, photoHint, videoHint, textHint,
                        this::allClick
                );
                break;
            case R.id.topBarRelative:
                finish();
                break;
            case R.id.tvModuleAbout:
                if (fileIds.isEmpty() && fileIdsText.isEmpty()) {
                    ToastUtil.showToast("请选择要操作的文件！");
                    return;
                }

                HomeFilesRelevantOperationDialog dialog = new HomeFilesRelevantOperationDialog(this);
                dialog.show();
                dialog.setOnBHClickListener(new OnBHClickListener() {
                    @Override
                    public void onConfirmClick() {
                        if (!fileIdsText.isEmpty()
                                || fileIds.size() != 1
                        ) {
                            ToastUtil.showToast("请选择单个图片或视频文件！");
                            return;
                        }

                        new RxPermissions(FamilyResActivity.this)
                                .request(
                                        Manifest.permission.READ_EXTERNAL_STORAGE,
                                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                                ).subscribe(new RxObserver<Boolean>() {
                            @Override
                            public void onNext(Boolean aBoolean) {
                                if (!aBoolean) {
                                    ToastUtil.showToast(R.string.picture_jurisdiction);
                                    return;
                                }

                                ImageBean bean = listItemLocations.get(0);
                                if (bean.type == 1) showShareDialog(bean.getUrl(), "image");
                                else showShareDialog(bean.getUrl(), "video");
                            }
                        });
                    }

                    @Override
                    public void onCloseClick() {
                        Intent intent = new Intent(FamilyResActivity.this, FamilySelectRelationActivity.class);
                        startActivityForResult(intent, REQUEST_CODE);
                    }
                });
                break;
            case R.id.ivModuleDelete:
                if (!fileIds.isEmpty() && !fileIdsText.isEmpty()) {
                    LogUtil.e("文本/图片/视频");
                    StringBuilder files = new StringBuilder();
                    for (String str : fileIds) {
                        files.append(str).append(",");
                    }

                    int fileSize = fileIds.size() + fileIdsText.size();
                    new HintDeleteDialog(this)
                            .setTitle("删除文件")
                            .setContent("是否删除" + fileSize + "项文件")
                            .setYes("确认删除")
                            .setOnBHClickListener(new OnBHClickListener() {
                                @Override
                                public void onConfirmClick() {
                                    deleteHomeFile(files.substring(0, files.length() - 1));
                                }
                            })
                            .show();
                } else if (!fileIdsText.isEmpty() && fileIds.isEmpty()) {
                    LogUtil.e("文本");
                    StringBuilder texts = new StringBuilder();

                    new HintDeleteDialog(this)
                            .setTitle("删除文件")
                            .setContent("是否删除" + fileIdsText.size() + "项文件")
                            .setYes("确认删除")
                            .setOnBHClickListener(new OnBHClickListener() {
                                @Override
                                public void onConfirmClick() {
                                    if (listItemLocationsText.size() != 0) {
                                        for (String str : fileIdsText) {
                                            texts.append(str).append(",");
                                        }
                                        deleteHomeText(texts.substring(0, texts.length() - 1));
                                    } else {
                                        LogUtil.e("listItemLocations条数为空");
                                    }
                                }
                            })
                            .show();
                } else if (!fileIds.isEmpty() && fileIdsText.isEmpty()) {
                    LogUtil.e("只有图片视频");
                    StringBuilder files = new StringBuilder();

                    new HintDeleteDialog(this)
                            .setTitle("删除文件")
                            .setContent("是否删除" + fileIds.size() + "项文件")
                            .setYes("确认删除")
                            .setOnBHClickListener(new OnBHClickListener() {
                                @Override
                                public void onConfirmClick() {
                                    for (String str : fileIds) {
                                        files.append(str).append(",");
                                    }
                                    deleteHomeFile(files.substring(0, files.length() - 1));
                                }
                            })
                            .show();
                } else {
                    ToastUtil.showToast("请选择要删除的文件！");
                }
                break;
            case R.id.ivModuleClock:
                ToastUtil.showToast("加密");
                break;
            case R.id.rightText:
                if (!isSHow) {
                    isSHow = true;
                    pos = 0;
                    for (String str : months) {
                        monthAdapter.setCheckBoxStatus(isSHow, pos++);
                        List<FamilyResCallbackBean.DataBeanX.DataBean> items = maps.get(str);
                        for (FamilyResCallbackBean.DataBeanX.DataBean item : items)
                            item.setChecked(false);
                    }
                    binding.rightText.setText("取消");
                    binding.llModuleBottom.setVisibility(View.VISIBLE);

                    fileIds.clear();
                    fileIdsText.clear();
                    listItemLocations.clear();
                    listItemLocationsText.clear();
                } else {
                    isSHow = false;
                    pos = 0;
                    for (String str : months) {
                        monthAdapter.setCheckBoxStatus(isSHow, pos++);
                    }
                    binding.rightText.setText("选择");
                    binding.llModuleBottom.setVisibility(View.GONE);
                }
                break;
            default:
        }
    }

    //分享弹窗
    public void showShareDialog(String mUrl, String type) {
        ShareDialog dialog = new ShareDialog(this, type);
        dialog.show();
        dialog.setOnShareStypeClickListener(
                style -> {
                    switch (style) {
                        case "Wx":
                            new ShareAction(FamilyResActivity.this)
                                    .setPlatform(SHARE_MEDIA.WEIXIN)
                                    .withText("河南传家宝")
                                    .withMedia(new UMImage(FamilyResActivity.this, mUrl))
                                    .share();
                            break;
                        case "QQ":
                            new ShareAction(FamilyResActivity.this)
                                    .setPlatform(SHARE_MEDIA.QQ)
                                    .withText("河南传家宝")
                                    .withMedia(new UMImage(FamilyResActivity.this, mUrl))
                                    .share();
                            break;
                        case "save":
                            downloadFile(mUrl, type);
                            break;
                    }
                }
        );
    }

    public void allClick(String type) {
        p = 1;
        this.type = type;
        getFamilyUserInfo(homeId, peopleId, true);
    }

    public void getSTS() {
        HTTPAPI.getInstance().getSTS(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (!StringUtil.isFail(s)) {
                    SpUtils.clear(FamilyResActivity.this);
                    startActivity(new Intent(FamilyResActivity.this, LoginActivity.class));
                    ActivityStack.getScreenManager().popAllActivityExceptOne(LoginActivity.class);
                    ToastUtil.showToast("登陆过期，请重新登陆");
                } else {
                    final STSCallBackBean bean = GsonUtil.GsonToBean(s, STSCallBackBean.class);

                    BHThreadPool.getInstance()
                            .executeTask(() -> {
                                        OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(
                                                bean.getData().getAccessKeyId(),
                                                bean.getData().getAccessKeySecret(),
                                                bean.getData().getSecurityToken());
                                        OSSLog.enableLog();
                                        oss = new OSSClient(
                                                FamilyResActivity.this,
                                                "https://" + bean.getData().getEndPoint(),
                                                credentialProvider,
                                                FApplication.getInstance().getClientConfiguration()
                                        );

                                        runOnUiThread(() -> binding.refreshLayout.autoRefresh());
                                    }
                            );
                }
            }
        });
    }

    int p = 1;
    String type = "";

    public void getFamilyUserInfo(final String id, String uid, boolean isClear) {
        binding.recycler.setFocusable(false);
        HTTPAPI.getInstance().getFamilyUserInfo(p++ + "", id, uid, type, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (!StringUtil.isFail(s)) {
                    p--;
                    StringUtil.showFail(FamilyResActivity.this, s);
                } else {
                    FamilyResCallbackBean listB = GsonUtil.GsonToBean(s, FamilyResCallbackBean.class);
                    listDataSecond = listB.getData().getData();
                    if (listDataSecond.size() == 0) {
                        cancelProgressDialog();
                        ToastUtil.showToast("暂无更多数据");
                    } else {
                        if (isClear) {
                            maps.clear();
                            months.clear();
                        }

                        for (FamilyResCallbackBean.DataBeanX.DataBean dataBean : listDataSecond) {
                            String createTime = dataBean.getCreate_time();

                            String dateNow = TimeHelper.getInstance().getNowTime("yyyy年MM月dd日");
                            String m = TimeHelper.getInstance()
                                    .stringToString(
                                            "yyyy-MM-dd HH:mm:ss",
                                            "yyyy年MM月dd日",
                                            createTime
                                    );

                            if (TextUtils.equals(dateNow, m)) {
                                m = "今天";
                            } else if (TextUtils.equals(
                                    dateNow.substring(0, 4),
                                    m.substring(0, 4)
                            )) {
                                m = TimeHelper.getInstance()
                                        .stringToString(
                                                "yyyy-MM-dd HH:mm:ss",
                                                "M月dd日",
                                                createTime
                                        );
                            }

                            bucketName = dataBean.getFile_bucket();
                            if (1 == dataBean.getFile_type()) {
                                GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(
                                        dataBean.getFile_bucket(),
                                        dataBean.getFile(),
                                        30 * 60,
                                        GET);
                                Map<String, String> map = new HashMap<>();
                                map.put("x-oss-process", dataBean.getParams().getXossprocess());
                                map.put("test", dataBean.getParams().getTest());
                                generatePresignedUrlRequest.setQueryParameter(map);
                                try {
                                    String url = oss.presignConstrainedObjectURL(generatePresignedUrlRequest);
                                    String urlShare = oss.presignConstrainedObjectURL(
                                            dataBean.getFile_bucket(),
                                            dataBean.getFile(),
                                            30 * 60
                                    );
                                    if (TextUtils.isEmpty(photoUrl)) photoUrl = url;
                                    dataBean.setThum(url);
                                    dataBean.setThumVideo(urlShare);
                                } catch (ClientException e) {
                                    e.printStackTrace();
                                }
                            } else if (2 == dataBean.getFile_type()) {
                                try {
                                    String urlVideo = oss.presignConstrainedObjectURL(
                                            dataBean.getFile_bucket(),
                                            dataBean.getFile(),
                                            30 * 60
                                    );
                                    String url = oss.presignConstrainedObjectURL(
                                            dataBean.getFile_bucket(),
                                            dataBean.getVideo_img(),
                                            60 * 60
                                    );
                                    if (TextUtils.isEmpty(videoUrl)) videoUrl = url;
                                    dataBean.setThum(url);
                                    dataBean.setThumVideo(urlVideo);
                                } catch (ClientException e) {
                                    e.printStackTrace();
                                }
                            }

                            if (!months.contains(m)) {
                                List<FamilyResCallbackBean.DataBeanX.DataBean> dataBeansList = new ArrayList<>();
                                dataBeansList.add(dataBean);
                                months.add(m);
                                maps.put(m, dataBeansList);
                            } else {
                                if (!maps.get(m).contains(dataBean)) {
                                    maps.get(m).add(dataBean);
                                }
                            }
                        }
                        monthAdapter.notifyDataSetChanged();
                        cancelProgressDialog();
                        getHomeFileTotal();
                    }
                }

                binding.refreshLayout.finishLoadMore();
                binding.refreshLayout.finishRefresh();
            }
        });
    }

    public void deleteHomeFile(String fileStr) {
        if (!TextUtils.isEmpty(fileStr)) {
            HTTPAPI.getInstance().deleteHomeFile(fileStr, new StringCallback() {
                @Override
                public void onSuccess(String s, Call call, Response response) {
                    if (!StringUtil.isFail(s)) {
                        StringUtil.showFail(FamilyResActivity.this, s);
                    } else {
                        try {
                            if ("people".equals(getIntent().getStringExtra("module_from"))) {
                                RefreshMessageEvent event = new RefreshMessageEvent();
                                event.setType("detail");
                                event.setId(getIntent().getStringExtra("module_type"));
                                EventBus.getDefault().post(event);
                            }

                            ArrayList<String> ids = new ArrayList<>();
                            for (ImageBean ib : listItemLocations) {
                                String key = months.get(ib.getFirst());
                                listDataSecond.clear();
                                listDataSecond.addAll(maps.get(key));
                                for (FamilyResCallbackBean.DataBeanX.DataBean familyBean : listDataSecond) {
                                    if (ib.getSecond() == familyBean.getId()) {
                                        if (listDataSecond.size() == 1) {
                                            maps.remove(key);
                                            ids.add(key);
                                        } else {
                                            maps.get(key).remove(familyBean);
                                        }
                                    }
                                }
                            }

                            if (!ids.isEmpty()) {
                                for (String innerKey : ids) months.remove(innerKey);
                                ids.clear();
                            }

                            monthAdapter.notifyDataSetChanged();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        fileIds.clear();
                        listItemLocations.clear();

                        if (!listItemLocationsText.isEmpty()) {
                            StringBuilder texts = new StringBuilder();
                            for (String str : fileIdsText) {
                                texts.append(str).append(",");
                            }
                            deleteHomeText(texts.substring(0, texts.length() - 1));
                        }
                    }
                }
            });
        }
    }

    public void deleteHomeText(final String fileIds) {
        HTTPAPI.getInstance().deleteHomeText(fileIds, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(FamilyResActivity.this, s);
                } else {
                    try {
                        ArrayList<String> ids = new ArrayList<>();
                        for (ImageBean ib : listItemLocationsText) {
                            String key = months.get(ib.getFirst());
                            listDataSecond.clear();
                            listDataSecond.addAll(maps.get(key));
                            for (FamilyResCallbackBean.DataBeanX.DataBean familyBean : listDataSecond) {
                                if (ib.getSecond() == familyBean.getId()) {
                                    if (listDataSecond.size() == 1) {
                                        maps.remove(key);
                                        ids.add(key);
                                    } else {
                                        maps.get(key).remove(familyBean);
                                    }
                                }
                            }
                        }

                        if (!ids.isEmpty()) {
                            for (String innerKey : ids) months.remove(innerKey);
                            ids.clear();
                        }

                        monthAdapter.notifyDataSetChanged();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    fileIdsText.clear();
                    listItemLocationsText.clear();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (REQUEST_CODE == requestCode) {
                String names = data.getStringExtra("module_bean");
                LogUtil.e("关联人-->" + names);
                if (!TextUtils.isEmpty(names)) {
                    homeFileRelation(names);
                }
            }
        }
    }

    public void homeFileRelation(String userIds) {
        showProgressDialog();
        StringBuilder files = new StringBuilder();
        if (fileIds.size() != 0) {
            for (String str : fileIds) {
                files.append(str).append(",");
            }
        }
        if (fileIdsText.size() != 0) {
            for (String str : fileIdsText) {
                files.append(str).append(",");
            }
        }

        HTTPAPI.getInstance().homeFileRelation(
                userIds,
                files.substring(0, files.length() - 1),
                new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        cancelProgressDialog();
                        if (!StringUtil.isFail(s)) {
                            StringUtil.showFail(FamilyResActivity.this, s);
                        } else {
                            ToastUtil.showToast("关联成功");
                            //释放资源
                            isSHow = false;
                            pos = 0;
                            for (String ignored : months) {
                                monthAdapter.setCheckBoxStatus(isSHow, pos++);
                            }
                            fileIdsText.clear();
                            fileIds.clear();
                            listItemLocations.clear();
                            listItemLocationsText.clear();
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        cancelProgressDialog();
                        LogUtil.e("关联失败" + e.getMessage());
                    }
                });
    }


    public void getHomeFileTotal() {
        HTTPAPI.getInstance().getHomeFileTotal("", new StringCallback() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(FamilyResActivity.this, s);
                } else {
                    FamilyFileTotalBean bean = GsonUtil.GsonToBean(s, FamilyFileTotalBean.class);
                    for (FamilyFileTotalBean.DataBean dataBean : bean.getData()) {
                        if (dataBean.getFile_type() == 1) {
                            photoHint = dataBean.getNum() + "";
                        } else if (2 == dataBean.getFile_type()) {
                            videoHint = dataBean.getNum() + "";
                        } else if (4 == dataBean.getFile_type()) {
                            textUrl = dataBean.getContent_intro();
                            textHint = dataBean.getNum() + "";
                        }
                    }
                }
            }
        });
    }

    private void downloadFile(String url, String type) {
        File appDir =
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
                        .getAbsoluteFile();
        if (!appDir.exists())
            //noinspection ResultOfMethodCallIgnored
            appDir.mkdir();

        String fileName = TextUtils.equals("image", type)
                ? "picture_" + System.currentTimeMillis() + ".jpg"
                : "video_" + System.currentTimeMillis() + ".mp4";

        HTTPAPI.getInstance().download(url, new FileCallback(
                appDir.getAbsolutePath(),
                fileName
        ) {
            @Override
            public void onBefore(BaseRequest request) {
                mDialog = new DowloadDialog(FamilyResActivity.this);
                mDialog.show();
            }

            @Override
            public void onSuccess(File file, Call call, Response response) {
                //发送广播通知系统图库刷新数据
                Uri uri = Uri.fromFile(file);
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                ToastUtil.showToast("已保存到相册！");
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                if (mDialog != null && mDialog.isShowing()) mDialog.dismiss();
                ToastUtil.showToast("文件下载失败！");
            }

            @Override
            public void downloadProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
                OkLogger.i("currentSize:" + currentSize);
                OkLogger.i("totalSize:" + totalSize);
                if (mDialog != null) mDialog.setProgress((int) (progress * 100));
            }

        });
    }

}
